package com.powernode.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.HashSet;

/**
 * swagger自动装配类
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;
    @Autowired
    private Environment environment;

    /*Swagger 的核心配置，负责生成 API 文档。
            new Docket(DocumentationType.OAS_30) 指定使用 OpenAPI 3.0 规范*/
    @Bean
    public Docket docket(){//只在开发环境有效
        try {
            boolean flag = true;
            String[] activeProfiles = environment.getActiveProfiles();
            for (String activeProfile : activeProfiles) {
                if (activeProfile.equals("pro")){//生产环境
                    flag = false;
                    break;
                }
            }
            return new Docket(DocumentationType.OAS_30)
                    .apiInfo(getApiInfo())
                    .enable(flag)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())).build();//扫描哪个包下的接口要生成文档
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    Contact contact = new Contact(
            swaggerProperties.getName(),
            swaggerProperties.getUrl(),
            swaggerProperties.getEmail()
    );
    /*getApiInfo() 方法返回一个 ApiInfo 对象，包含有关 API 的元数据，
    如标题、描述、版本、许可证等。这些信息会在生成的 API 文档中显示*/
    private ApiInfo getApiInfo() {

        try {
            ApiInfo apiInfo = new ApiInfo(
                    swaggerProperties.getTitle(),
                    swaggerProperties.getDescription(),
                    swaggerProperties.getVersion(),
                    swaggerProperties.getTermsOfServiceUrl(),
                    contact,
                    swaggerProperties.getLicense(),
                    swaggerProperties.getLicenseUrl(),
                    new HashSet<>());
            return apiInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
